<script setup>
import { ref, reactive, computed, watchEffect, watch } from 'vue'
import { userService } from '../../services/user'
import { roleService } from '../../services/role'

const props = defineProps({
  editMode: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['confirm', 'closed'])

// 对话框可见状态
const dialogVisible = ref(false)

// 对话框标题
const dialogTitle = computed(() => props.editMode ? '编辑用户' : '添加用户')

// 表单数据
const formData = reactive({
  id: '',
  username: '',
  password: '',
  confirm_password: '',
  real_name: '',
  email: '',
  phone: '',
  status: 1,
  roles: []
})

// 表单规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  real_name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  roles: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 角色列表
const roleList = ref([])

// 获取角色列表
const fetchRoles = async () => {
  try {
    const { data } = await roleService.getRoles()
    roleList.value = data || []
  } catch (error) {
    console.error('Failed to fetch roles:', error)
  }
}

// 表单引用
const formRef = ref(null)

// 打开对话框
const openDialog = () => {
  dialogVisible.value = true
  // 获取角色列表
  fetchRoles()
  
  // 填充表单数据
  fillFormData()
}

// 填充表单数据
const fillFormData = () => {
  // 如果是编辑模式，填充表单数据
  if (props.editMode && props.editData) {
    console.log('Filling form data with:', props.editData)
    Object.keys(formData).forEach(key => {
      if (key !== 'password' && key !== 'confirm_password') {
        if (key === 'roles') {
          formData.roles = props.editData.roles?.map(role => role.id) || []
        } else if (props.editData[key] !== undefined) {
          formData[key] = props.editData[key]
        }
      }
    })
  } else {
    // 新增模式，重置表单
    resetForm()
  }
}

// 监听编辑数据变化
watch(() => props.editData, (newVal) => {
  if (newVal && dialogVisible.value) {
    console.log('EditData changed, updating form:', newVal)
    fillFormData()
  }
}, { deep: true })

// 监听编辑模式变化
watch(() => props.editMode, (newVal) => {
  if (dialogVisible.value) {
    if (newVal) {
      fillFormData()
    } else {
      resetForm()
    }
  }
})

// 重置表单
const resetForm = () => {
  Object.keys(formData).forEach(key => {
    if (key === 'status') {
      formData[key] = 1
    } else {
      formData[key] = ''
    }
  })
  formData.roles = []
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 构造提交数据
    const submitData = { ...formData }
    
    // 确保phone是字符串类型
    if (submitData.phone) {
      submitData.phone = String(submitData.phone)
    }
    
    // 编辑模式不需要提交密码
    if (props.editMode) {
      delete submitData.password
      delete submitData.confirm_password
    }
    
    emit('confirm', submitData)
    dialogVisible.value = false
  } catch (error) {
    console.error('Form validation failed:', error)
  }
}

// 取消
const cancelDialog = () => {
  dialogVisible.value = false
}

// 对话框关闭后触发事件
const handleClosed = () => {
  emit('closed')
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 暴露给父组件的方法
defineExpose({
  openDialog
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="500px"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名" />
      </el-form-item>
      
      <template v-if="!editMode">
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input
            v-model="formData.confirm_password"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
      </template>
      
      <el-form-item label="姓名" prop="real_name">
        <el-input v-model="formData.real_name" placeholder="请输入姓名" />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱" />
      </el-form-item>
      
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号" />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="角色" prop="roles">
        <el-select
          v-model="formData.roles"
          multiple
          placeholder="请选择角色"
          style="width: 100%"
        >
          <el-option
            v-for="role in roleList"
            :key="role.id"
            :label="role.name"
            :value="role.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 